﻿using System;
using GeoAPI.Geometries;
using YJKGridTopologyCal.Geometries.Utilities;

namespace YJKGridTopologyCal.Operation.Overlay.Snap
{
	internal class SnapTransformer : GeometryTransformer
	{
		public SnapTransformer(double snapTolerance, Coordinate[] snapPts)
		{
			this._snapTolerance = snapTolerance;
			this._snapPts = snapPts;
		}

		public SnapTransformer(double snapTolerance, Coordinate[] snapPts, bool isSelfSnap) : this(snapTolerance, snapPts)
		{
			this._isSelfSnap = isSelfSnap;
		}

		protected override ICoordinateSequence TransformCoordinates(ICoordinateSequence coords, IGeometry parent)
		{
			Coordinate[] srcPts = coords.ToCoordinateArray();
			Coordinate[] coordinates = this.SnapLine(srcPts, this._snapPts);
			return this.Factory.CoordinateSequenceFactory.Create(coordinates);
		}

		private Coordinate[] SnapLine(Coordinate[] srcPts, Coordinate[] snapPts)
		{
			return new LineStringSnapper(srcPts, this._snapTolerance)
			{
				AllowSnappingToSourceVertices = this._isSelfSnap
			}.SnapTo(snapPts);
		}

		private readonly double _snapTolerance;

		private readonly Coordinate[] _snapPts;

		private readonly bool _isSelfSnap;
	}
}
